/**
 * Copyright (c) 2011-2016, hubin (jobob@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.ITypeConvert;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;


/**
 * <p>
 * 代码生成器演示
 * </p>
 *
 * @author hubin
 * @date 2016-12-01
 */
public class MysqlGenerator {
	//public final static String rootPath = "E:\\workspace\\tianshi-parent\\tianshi-common" ;  黄子明
	public final static String rootPath = "E:\\happy-dog-pay\\happy-dog\\happy-dog-common" ; //田鹏 windows环境
	//private final  static String rootPath = "/Users/tianpeng/happy-dog-pay/happy-dog/happy-dog-common"; //田鹏 mac关键
    private final static String modelName="pay";
    private final static  String packName="com";
    private final static  String javaPath=rootPath+"/src/main/java";
    private final  static  String xmlPath=rootPath+"/src/main/resources/mapper";
    /**
     * <p>
     * MySQL 生成演示
     * </p>
     */
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(javaPath);
        gc.setFileOverride(true);
        gc.setActiveRecord(false);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setAuthor("Peng");
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        // gc.setMapperName("%sDao");
        // gc.setXmlName("%sDao");
        // gc.setServiceName("MP%sService");
        // gc.setServiceImplName("%sServiceDiy");
        // gc.setControllerName("%sAction");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setTypeConvert(new ITypeConvert() {
			@Override
			//无论时间是什么类型在java里面都要是java.util.Date类型
			public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
				String t = fieldType.toLowerCase();
		        if (t.contains("char") || t.contains("text")) {
		            return DbColumnType.STRING;
		        } else if (t.contains("bigint")) {
		            return DbColumnType.LONG;
		        } else if (t.contains("tinyint(1)")) {
		            return DbColumnType.BOOLEAN;
		        } else if (t.contains("int")) {
		            return DbColumnType.INTEGER;
		        } else if (t.contains("text")) {
		            return DbColumnType.STRING;
		        } else if (t.contains("bit")) {
		            return DbColumnType.BOOLEAN;
		        } else if (t.contains("decimal")) {
		            return DbColumnType.BIG_DECIMAL;
		        } else if (t.contains("clob")) {
		            return DbColumnType.CLOB;
		        } else if (t.contains("blob")) {
		            return DbColumnType.BLOB;
		        } else if (t.contains("binary")) {
		            return DbColumnType.BYTE_ARRAY;
		        } else if (t.contains("float")) {
		            return DbColumnType.FLOAT;
		        } else if (t.contains("double")) {
		            return DbColumnType.DOUBLE;
		        } else if (t.contains("json") || t.contains("enum")) {
		            return DbColumnType.STRING;
		        } else if (t.contains("date") || t.contains("time") || t.contains("year")) {
		            switch (globalConfig.getDateType()) {
		                case ONLY_DATE:
		                    return DbColumnType.DATE;
		                case SQL_PACK:
		                    switch (t) {
		                        case "date":
		                            return DbColumnType.DATE;
		                        case "time":
		                            return DbColumnType.DATE;
		                        case "year":
		                            return DbColumnType.DATE;
		                        default:
		                            return DbColumnType.DATE;
		                    }
		                case TIME_PACK:
		                    switch (t) {
		                        case "date":
		                            return DbColumnType.DATE;
		                        case "time":
		                            return DbColumnType.DATE;
		                        case "year":
		                            return DbColumnType.DATE;
		                        default:
		                            return DbColumnType.DATE;
		                    }
		            }
		        }
		        return DbColumnType.STRING;
			}
		}) ;
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("Panzer520456!");
        dsc.setUrl("jdbc:mysql://39.108.174.14/happy_dog?tinyInt1isBit=false&characterEncoding=utf8&serverTimezone=UTC&useSSL=false");
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();

        // strategy.setCapitalMode(true);// 全局大写命名
        strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        
        strategy.setInclude(new String[] {"t_cash_rule"}); // 需要生成的表
        //改上面就好了↑
        
        strategy.setVersionFieldName("version") ; //乐观锁字段
        strategy.setLogicDeleteFieldName("isdel") ; //逻辑删除字段
        
        
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        //自定义实体父类
        //strategy.setSuperEntityClass("com.chl.utils.BasePage");
        //自定义实体，公共字段
        //strategy.setSuperEntityColumns(new String[] { "name", "age" }); 
        // 自定义 mapper 父类
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定义 service 父类
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定义 service 实现类父类
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定义 api 父类
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // 【实体】是否生成字段常量（默认 false）
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // 【实体】是否为构建者模型（默认 false）
        // public User setName(String name) {this.name = name; return this;}
        // strategy.setEntityBuliderModel(true);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(modelName);
        pc.setParent(packName);// 自定义包路径
        //pc.setController("api");// 这里是控制器包名，默认 cloud
        mpg.setPackageInfo(pc);

        // 注入自定义配置，可以在 VM 中使用 cfg.abc 设置的值
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String,Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return  xmlPath+"/" +tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 关闭默认 xml 生成，调整生成 至 根目录
        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        mpg.setTemplate(tc);

        // 自定义模板配置，模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
        // 至您项目 src/main/resources/template 目录下，模板名称也可自定义如下配置：
        // TemplateConfig tc = new TemplateConfig();
        // tc.setController("...");
        // tc.setEntity("...");
        // tc.setMapper("...");
        // tc.setXml("...");
        // tc.setService("...");
        // tc.setServiceImpl("...");
        // mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();

        // 打印注入设置
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }

}
